from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import time, datetime

from google.appengine.api import users

from django.utils import simplejson

from voteDb import voteDB

class NotFoundPageHandler(webapp.RequestHandler):
  def get(self):
    self.error(404)
    self.response.out.write('Not found.')

#    userid = self.request.get("userid")
#    user = users.get_current_user()
#    if user:
#      admin = voteDB.AdminCheck(user.email())
#      if admin:
#      else:
#        self.error(401)
#        self.response.out.write("You are not an Admin user.")
#    else:
#      self.error(401)
#      self.response.out.write("Not Authorised")

class WorkIndex(webapp.RequestHandler):
  def get(self):
    rtv = voteDB.WorkLen('work_in')
    self.response.out.write(rtv)

class WorkAdd(webapp.RequestHandler):
  def get(self):
    args = self.request.arguments()
    gets = {}
    for a in args:
      gets[a] = self.request.get(a)
    rtv = voteDB.WorkAdd('work_in', {'gets': gets})
    self.response.out.write(rtv)

  def post(self):
    args = self.request.arguments()
    posts = {}
    for a in args:
      posts[a] = self.request.post(a)
    rtv = voteDB.WorkAdd('work_in', {'posts': posts})
    self.response.out.write(rtv)

class WorkGet(webapp.RequestHandler):
  def get(self):
    defaultnum = 1
    num = self.request.get("num")
    if num == None or num == "":
      n = defaultnum
    else:
      if num > 0:
        n = num
      else:
        n = defaultnum
    rtv = simplejson.dumps(voteDB.WorkGet('work_in', int(n)))
    self.response.out.write(rtv)

application = webapp.WSGIApplication(
  [
    ('/work/', WorkIndex),
    ('/work/add', WorkAdd), # params: All GET/POST
    ('/work/get', WorkGet), # params: num:default 1
    ('/.*', NotFoundPageHandler)
  ], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
